package com.itheima.d6_synchronized_lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Ticket2 implements Runnable {
    private static int ticket = 100;
    private static int sum = 0;
    private final Lock lk = new ReentrantLock();

    @Override
    public void run() {
        while (true) {
            try {
                lk.lock();
                if (ticket <= 0) {
                    break;
                } else {
                    ticket--;
                    System.out.println(Thread.currentThread().getName() + "在卖票，还剩 " + ticket + " 张" + "\t总卖：" + ++sum);
                }
                Thread.sleep(10);
            }catch (Exception e){
                e.printStackTrace();
            }
            finally {
                lk.unlock();
            }

        }
    }

    public synchronized boolean sellTicket1() {
        if (ticket <= 0) {
            return true;
        } else {
            ticket--;
            System.out.println(Thread.currentThread().getName() + "在卖票，还剩 " + ticket + " 张" + "\t总卖：" + ++sum);
            return false;
        }
    }

    public static synchronized boolean sellTicket2() {
        if (ticket <= 0) {
            return true;
        } else {
            ticket--;
            System.out.println(Thread.currentThread().getName() + "在卖票，还剩 " + ticket + " 张" + "总卖：" + ++sum);
            return false;
        }
    }

}
